package com.trainoo.alert.service;

import com.alibaba.fastjson.JSONObject;
import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;
import org.apache.velocity.runtime.RuntimeConstants;
import org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import javax.mail.internet.MimeMessage;
import java.io.StringWriter;
import java.util.Properties;

/**
 * @Auther: zt
 * @Date: 2020/4/8 17:42
 * @Description:
 */
@Service
public class SendEmailService  implements IService {

    private static final Logger LOG = LoggerFactory.getLogger(SendEmailService.class);
    private static final String EMAIL_TEMPLATE_VM_PATH = "template/mail.html";

    @Autowired
    private JavaMailSender javaMailSender;

    @Value("${spring.mail.to}")
    private String toMail;

    @Value("${spring.mail.from}")
    private String fromMail;

    /**
     * velocity模板
     */
    private Template template;

    /**
     * 初始化velocity模板
     */
    @PostConstruct
    private void init() {
        Properties p = new Properties();
        p.setProperty(RuntimeConstants.RESOURCE_LOADER, "classpath");
        p.setProperty("classpath.resource.loader.class", ClasspathResourceLoader.class.getName());
        Velocity.init(p);
        template = Velocity.getTemplate(EMAIL_TEMPLATE_VM_PATH, "UTF-8");
    }

    /**
     * 发送velocity模板(HTML)邮件
     */
    @Override
    public void alert(String mailData) {
        // 填充模板,作为内容
        JSONObject data = JSONObject.parseObject(mailData);
        final String subject = formatSubject(data);
        final String content = formatTemplate(data);
        LOG.debug("开始发送告警邮件，邮件名[{}], 邮件正文[{}]", subject, content);
        // 发送邮件
        MimeMessage mimeMessage = javaMailSender.createMimeMessage();
        MimeMessageHelper helper;
        try {
            helper = new MimeMessageHelper(mimeMessage, true);
            helper.setFrom(fromMail);
            helper.setTo(toMail);
            helper.setSubject(subject);
            helper.setText(content, true);
            javaMailSender.send(mimeMessage);
        } catch (Exception e) {
            LOG.error("发送邮件告警信息异常", e);
        }
    }

    private String formatSubject(JSONObject data) {
        return String.format("服务器[%s]发生告警，请及时处理", data.get("host"));
    }

    private String formatTemplate(JSONObject data){
        VelocityContext context = new VelocityContext();
        context.put("time", data.get("@timestamp"));
        context.put("host", data.get("host"));
        context.put("rule", data.get("rule"));
        context.put("message", data.get("message"));
        StringWriter sw = new StringWriter();
        this.template.merge(context,sw);
        return sw.toString();
    }
}
